package com.kafka.kafkatest.util;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.kafka.kafkatest.handler.KafkaSendResultHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import javax.annotation.Resource;

@Component
@Slf4j
public class KafkaProducer {
    @Resource
    private KafkaTemplate<String, Object> kafkaTemplate;

    @Autowired
    private KafkaSendResultHandler resultHandler;

    public static final String TOPIC_TEST = "aigc";

    public static final String AGI_TEST = "agi";

    public static final String TOPIC_GROUP = "aigc";

    public void sendAigcMsg(Object obj) {
        String obj2String = JSON.toJSONString(obj);
        String key= UUID.fastUUID().toString();
        log.info("准备发送消息为：{},key：{}", obj2String,key);
        // 发送消息
//        kafkaTemplate.send(TOPIC_TEST,key, obj);
//        kafkaTemplate.send(TOPIC_TEST,key, obj);
//                .addCallback(resultHandler);
        log.info("消息发送成功！消息id:{}", key);
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(AGI_TEST,key, obj);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                //发送失败的处理
                log.info(TOPIC_TEST + " - 生产者 发送消息失败：" + throwable.getMessage());
            }
            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                //成功的处理
                log.info(TOPIC_TEST + " - 生产者 发送消息成功：" + stringObjectSendResult.toString());
            }
        });
    }
}
